package top.littlejiang.onlinexam.common.utils;

import top.littlejiang.onlinexam.common.base.BaseTree;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;


/**
 * @author chen
 * @Description
 * @since 2020/12/26 16:31
 */
public class BuildTreeUtils {

	public static <T> List<T> buildList(List<? extends BaseTree<T>> nodes, Serializable idParam) {
		if (nodes == null) {
			return null;
		}
		List<BaseTree<T>> topNodes = new ArrayList<>();

		for (BaseTree<T> children : nodes) {

			Serializable pid = children.getParentId();
			if (pid == null || idParam.equals(pid)) {
				topNodes.add(children);
				continue;
			}
            children(nodes, children, pid);
        }
		return (List<T>) topNodes;
	}

    private static <T> void children(List<? extends BaseTree<T>> nodes, final BaseTree<T> children, final Serializable pId) {
		nodes.stream().filter(node -> node.getId() != null && node.getId().equals(pId)).forEach(node -> {
			node.getChildren().add(children);
		});
    }

}
